import React, { useEffect, useState } from 'react';
import { Form, Dialog, TreeSelect } from 'tdesign-react';
import { FormProps } from 'tdesign-react';
import { JupiterRolePermisson, JupiterPermission, JupiterRole } from '../../../types/roleTypes';

const { FormItem } = Form;

interface Props {
    visible: boolean;
    onClose: () => void;
    onSubmit: (data: Partial<JupiterRolePermisson>) => void;
    initialData?: Partial<JupiterRole>;
    title: string;
    permissionTree: JupiterPermission[]; // 后端查询到的权限树
    permissionIds: string[]; // 当前角色已关联的权限ID
}

export default function RolePermissionForm({
    visible,
    onClose,
    onSubmit,
    initialData = {},
    title,
    permissionTree,
    permissionIds,
}: Props) {
    const [form] = Form.useForm();
    const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);

    // 每次打开 dialog 填充初始数据
    useEffect(() => {
        if (visible) {
            form.reset();
            // form.setFieldsValue({
            //     name: initialData?.name || '',
            //     description: initialData?.description || '',
            // });
            setSelectedPermissions(permissionIds || []);
        }
    }, [visible, permissionIds, initialData, form]);

    const handleSubmit: FormProps['onSubmit'] = ({ validateResult, fields }) => {
        if (validateResult === true) {
            onSubmit({
                roleUuid: initialData?.uuid,
                permissionUuids: selectedPermissions,
            });
        }
    };

    const handleClose = () => {
        form.reset();
        setSelectedPermissions([]);
        onClose();
    };

    return (
        <Dialog
            closeOnOverlayClick={false}
            header={title}
            visible={visible}
            onClose={handleClose}
            onConfirm={() => form.submit()}
            width={600}
        >
            <Form form={form} layout="vertical" onSubmit={handleSubmit}>

                <FormItem label="关联权限">
                    <TreeSelect
                        // value={permissionIds}
                        // onChange={(value) => setSelectedPermissions(value as string[])}
                        data={permissionTree}
                        multiple
                        placeholder="请选择权限"
                        treeProps={{
                            checkable: true,
                            value: selectedPermissions, // 关键点：要放在 treeProps 里
                            onChange: (newValue) => {
                                setSelectedPermissions(newValue as string[]);
                            },
                        }}
                        style={{ width: '70%' }}
                        popupProps={{
                            overlayStyle: { minWidth: 'auto' }, // 避免默认 100%
                        }}
                    />
                </FormItem>
            </Form>
        </Dialog>
    );
}
